/**
 * @Title: table-form-teacher.js
 * @Description: table-form
 * @author: Fanchao
 * @date: 2020/8/26 11:13 上午
 * @version V1.0
 */

import React, { useState } from "react";
import { PlusOutlined } from "@ant-design/icons";
import { Button, Divider, Input, Popconfirm, Table, message } from "antd";
import { connect } from "umi";

const TableForm = ({ isAdmin, questions: { questionList, evaluatePlanIdOption, evaluateQuestionTypeOption, selectedRowKeys }, loadingReload, dispatch }) => {
    const [clickedCancel, setClickedCancel] = useState(false);
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState([]);
    const [index, setIndex] = useState(0);
    const [cacheOriginData, setCacheOriginData] = useState({});
    const getRowByKey = (evaluateQuestionId, newData) => (newData || questionList)?.filter((item) => item.evaluateQuestionId === evaluateQuestionId)[0];

    const toggleEditable = (e, evaluateQuestionId) => {
        e.preventDefault();
        const newData = questionList?.map((item) => ({ ...item }));
        const target = getRowByKey(evaluateQuestionId, newData);
        if (target) {
            if (!target.editable) {
                cacheOriginData[evaluateQuestionId] = { ...target };
                setCacheOriginData(cacheOriginData);
            }
            target.editable = !target.editable;
            dispatch({
                type: "questions/setQuestionList",
                payload: {
                    questionList: newData
                }
            });
            setData(newData);
        }
    };
    const remove = (evaluateQuestionId) => {
        const newData = questionList?.filter((item) => item.evaluateQuestionId !== evaluateQuestionId);
        dispatch({
            type: "questions/setQuestionList",
            payload: {
                questionList: newData
            }
        });
    };
    const deleteThis = (evaluateQuestionId) => {
        dispatch({
            type: "questions/deleteEvaluateQuestion",
            payload: { evaluateQuestionId },
            callback: (result) => {
                if (result) {
                    dispatch({
                        type: "questions/getQuestionList",
                        payload: {
                            evaluatePlanId: evaluatePlanIdOption.value,
                            questionCategoryName: evaluateQuestionTypeOption.value
                        }
                    });
                }
            }
        });
    };
    const handleFieldChange = (e, fieldName, evaluateQuestionId) => {
        const newData = [...(data)];
        const target = getRowByKey(evaluateQuestionId, newData);
        if (target) {
            target[fieldName] = e.target.value;
            setData(newData);
        }
    };
    const saveRow = (e, evaluateQuestionId) => {
        e.persist();
        if (clickedCancel) {
            setClickedCancel(false);
            return;
        }
        const target = getRowByKey(evaluateQuestionId) || ({});
        if (!target.checkPoint || !target.category || !target.weight) {
            message.error("请填写完整成员信息");
            (e.target).focus();
            setLoading(false);
            return;
        }
        delete target.isNew;
        delete target.editable;
        delete target.evaluatePlanId;
        delete target.evaluatePlanName;
        dispatch({
            type: "questions/editEvaluateQuestion",
            payload: target,
            callback: (result) => {
                if (result) {
                    dispatch({
                        type: "questions/getQuestionList",
                        payload: {
                            evaluatePlanId: evaluatePlanIdOption ? evaluatePlanIdOption.value : "",
                            questionCategoryName: evaluateQuestionTypeOption ? evaluateQuestionTypeOption.value : ""
                        }
                    });
                }
            }
        });
    };
    const newMember = () => {
        if (!evaluatePlanIdOption || !evaluateQuestionTypeOption) {
            message.warn("请选择评价等级或者评教类型");
            return;
        }
        const newData = questionList?.map((item) => ({ ...item })) || [];
        newData.push({
            evaluateQuestionId: `${index}`,
            checkPoint: "",
            category: "",
            weight: "",
            evaluatePlanName: evaluatePlanIdOption.label,
            editable: true,
            isNew: true
        });
        dispatch({
            type: "questions/setQuestionList",
            payload: {
                questionList: newData,
                evaluatePlanId: evaluatePlanIdOption.value,
                evaluateQuestionType: evaluateQuestionTypeOption.value
            }
        });
        setIndex(index + 1);
        setData(newData);
    };
    const addRow = (e, evaluateQuestionId) => {
        e.persist();
        if (clickedCancel) {
            setClickedCancel(false);
            return;
        }
        const target = getRowByKey(evaluateQuestionId) || ({});
        if (!target.checkPoint || !target.category || !target.weight) {
            message.error("请填写完整题目信息");
            (e.target).focus();
            setLoading(false);
            return;
        }
        target.evaluatePlanId = evaluatePlanIdOption.value;
        target.questionCategoryName = evaluateQuestionTypeOption.value;
        target.sort = target.evaluateQuestionId;
        delete target.isNew;
        delete target.editable;
        dispatch({
            type: "questions/addEvaluateQuestion",
            payload: target,
            callback: (result) => {
                if (result) {
                    dispatch({
                        type: "questions/getQuestionList",
                        payload: {
                            evaluatePlanId: evaluatePlanIdOption.value,
                            questionCategoryName: evaluateQuestionTypeOption.value
                        }
                    });
                }
            }
        });
    };
    const handleKeyPress = (e, evaluateQuestionId) => {
        if (e.key === "Enter") {
            saveRow(e, evaluateQuestionId);
        }
    };
    const cancel = (e, key) => {
        setClickedCancel(true);
        e.preventDefault();
        const newData = [...(questionList)];
        // 编辑前的原始数据
        let cacheData = [];
        cacheData = newData.map((item) => {
            if (item.key === key) {
                if (cacheOriginData[key]) {
                    const originItem = {
                        ...item,
                        ...cacheOriginData[key],
                        editable: false
                    };
                    delete cacheOriginData[key];
                    setCacheOriginData(cacheOriginData);
                    return originItem;
                }
            }
            return item;
        });
        dispatch({
            type: "questions/setQuestionList",
            payload: {
                questionList: cacheData
            }
        });
        setData(cacheData);
        setClickedCancel(false);
    };
    const columns = [
        {
            title: "评价指标",
            dataIndex: "category",
            width: "20%",
            align: "left",
            render: (text, record) => {
                if (record.editable) {
                    return (
                        <Input
                            value={text}
                            autoFocus
                            onChange={(e) => handleFieldChange(e, "category", record.evaluateQuestionId)}
                            onKeyPress={(e) => handleKeyPress(e, record.evaluateQuestionId)}
                            placeholder="评价指标"
                        />
                    );
                }
                return text;
            }
        },
        {
            title: "评价标准",
            dataIndex: "checkPoint",
            width: "20%",
            align: "left",
            render: (text, record) => {
                if (record.editable) {
                    return (
                        <Input
                            value={text}
                            onChange={(e) => handleFieldChange(e, "checkPoint", record.evaluateQuestionId)}
                            onKeyPress={(e) => handleKeyPress(e, record.evaluateQuestionId)}
                            placeholder="评价标准"
                        />
                    );
                }
                return text;
            }
        },
        {
            title: "权重",
            dataIndex: "weight",
            width: "20%",
            align: "left",
            render: (text, record) => {
                if (record.editable) {
                    return (
                        <Input
                            value={text}
                            onChange={(e) => handleFieldChange(e, "weight", record.evaluateQuestionId)}
                            onKeyPress={(e) => handleKeyPress(e, record.evaluateQuestionId)}
                            placeholder="权重"
                        />
                    );
                }
                return text;
            }
        },
        {
            title: "评价等级",
            dataIndex: "evaluatePlanName",
            width: "20%",
            align: "left",
            render: (text, record) => {
                if (record.editable) {
                    return (
                        <Input
                            disabled={true}
                            value={text}
                            onChange={(e) => handleFieldChange(e, "evaluatePlanId", record.evaluateQuestionId)}
                            onKeyPress={(e) => handleKeyPress(e, record.evaluateQuestionId)}
                            placeholder="评价等级"
                        />
                    );
                }
                return text;
            }
        },
        isAdmin ? (
            {
                title: "操作",
                align: "left",
                render: (text, record) => {
                    if (!!record.editable && loading) {
                        return null;
                    }
                    if (record.editable) {
                        if (record.isNew) {
                            return (
                                <div>
                                    <a onClick={(e) => addRow(e, record.evaluateQuestionId)}>保存</a>
                                    <Divider type="vertical"/>
                                    <Popconfirm title="是否要删除？"
                                                onConfirm={() => remove(record.evaluateQuestionId)}>
                                        <a style={{ color: "#C21217" }}>删除</a>
                                    </Popconfirm>
                                </div>
                            );
                        }
                        return (
                            <div>
                                <a onClick={(e) => saveRow(e, record.evaluateQuestionId)}>保存</a>
                                <Divider type="vertical"/>
                                <a onClick={(e) => cancel(e, record.key)}>取消</a>
                            </div>
                        );
                    }
                    return (
                        <div>
                            <a onClick={(e) => toggleEditable(e, record.evaluateQuestionId)}>编辑</a>
                            <Divider type="vertical"/>
                            <Popconfirm title="是否要删除？" onConfirm={() => deleteThis(record.evaluateQuestionId)}>
                                <a style={{ color: "#C21217" }}>删除</a>
                            </Popconfirm>
                        </div>
                    );
                }
            }
        ) : {}
    ];
    const onSelectChange = (selectedRowKeys) => {
        dispatch({
            type: "questions/setSelectedRowKeys",
            payload: selectedRowKeys
        });
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange
    };
    return (
        <>
            <Table
                rowSelection={(evaluatePlanIdOption && evaluateQuestionTypeOption && isAdmin) ? rowSelection : null}
                loading={loadingReload}
                columns={columns}
                dataSource={questionList}
                pagination={false}
            />
            {
                isAdmin ? (
                    <Button
                        style={{ width: "100%", marginTop: 16, marginBottom: 8 }}
                        type="dashed"
                        onClick={newMember}
                    >
                        <PlusOutlined/>
                        {
                            questionList.length === 0 ? "添加题目" : "继续添加"
                        }
                    </Button>
                ) : null
            }
        </>
    );
};

export default connect(({ questions, dispatch, loading }) => ({
    questions,
    dispatch,
    loadingReload: loading.effects["questions/getQuestionList"]
}))(TableForm);
